package cn.com.easyfelling.utils;

import java.sql.Connection;

/**
 * 封装事务
 */
public class Transaction {
  public static void begin(){
    Connection connection = DBUtilsBindThread.getConnection();
    try {
      // 开启事务
      connection.setAutoCommit(false);
    }catch (Exception e){
      e.printStackTrace();
    }
  }
  public static void commit(){
    Connection connection = DBUtilsBindThread.getConnection();
    try {
      // 提交事务
      connection.commit();
      connection.close();
    }catch (Exception e){
      e.printStackTrace();
    }
  }
  public static void rollback(){
    Connection connection = DBUtilsBindThread.getConnection();
    try {
      // 回滚事务
      connection.rollback();
      connection.close();
    }catch (Exception e){
      e.printStackTrace();
    }
  }
  public static void close(){
    Connection connection = DBUtilsBindThread.getConnection();
    try {
      // 恢复自动提交
      connection.setAutoCommit(true);
      // 原生的close会关闭链接。如果是连接池(DataSource)，则只是归还连接
      connection.close();
      // 关闭连接之后再删除线程中的链接
      DBUtilsBindThread.threadLocal.remove();
    }catch (Exception e){
      e.printStackTrace();
    }
  }
}
